/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.io.IOException;
import java.util.List;

import org.json.JSONException;

import kr.pe.johnkim.dayve.provider.DayveLog;
import kr.pe.johnkim.dayve.provider.DayveMember;
import kr.pe.johnkim.dayve.rest.DayveCommonRest;
import kr.pe.johnkim.dayve.rest.DayveMemberRest;
import kr.pe.johnkim.dayve.util.DayveCommon;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 사용자의 이메일 주소를 변경하는 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class DayveChangeEmailView extends Activity {

	public static String TAG = DayveChangeEmailView.class.getSimpleName();
	
	ProgressBar progressBarChangeEmail;
	
	TextView txtViewChangeEmailNotification;
	
	EditText edtTextChangeEmail;
	
	Button btnChangeEmail;
	
	// 설정 파일을 가져 온다.
	private String myPreference = "kr.pe.johnkim.dayve.activity_preferences";

	private String DAYVE_ID = "";
	private String DAYVE_PASSWORD = "";
	private String DAYVE_EMAIL = "";
	private String currentDate = "";
	
	DayveMemberRest dayveMemberRest = new DayveMemberRest();
	DayveCommonRest dayveCommonRest = new DayveCommonRest();
	DayveCommon dayveCommon = new DayveCommon();

	// 프로그레스 바를 출력 한다.
	private static final int THREAD_PROGRESS_BAR_VISIBLE = 101;

	// 프로그레스 바를 감춘다.
	private static final int THREAD_PROGRESS_BAR_INVISIBLE = 102;

	// 이메일을 변경한다.
	private static final int THREAD_CHANGE_EMAIL = 103;

	// 이메일 변경에 성공하면 toast 를 띄운다.
	private static final int THREAD_CHANGE_EMAIL_SUCCESS = 104;

	// 이메일 변경에 실패하면 dialog 창을 띄운다.
	private static final int THREAD_CHANGE_EMAIL_FAIL = 105;

	private String RESULT_CHANTE_EMAIL = "";

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dayve_change_email);
		
		confirmNotification();
		
		// 현재 시간을 가져 온다.
		currentDate = dayveCommon.getCurrentDate();
		
		progressBarChangeEmail = (ProgressBar)findViewById(R.id.progressBarChangeEmail);
		
		txtViewChangeEmailNotification = (TextView)findViewById(R.id.txtViewChangeEmailNotification);
		
		// 이메일 초기값을 세팅 한다.
		edtTextChangeEmail = (EditText)findViewById(R.id.edtTextChangeEmail);
		edtTextChangeEmail.setText(DAYVE_EMAIL);
		
		btnChangeEmail = (Button)findViewById(R.id.btnChangeEmail);
		btnChangeEmail.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				// TODO Auto-generated method stub
				if(("").equals(edtTextChangeEmail.getText().toString().trim())) {
					new AlertDialog.Builder(DayveChangeEmailView.this)
					.setTitle(getResources().getString(R.string.change_email_enter_email_title))
					.setMessage(getResources().getString(R.string.change_email_enter_email_message))
					.setPositiveButton(getResources().getString(R.string.change_email_enter_email_button_ok), 
						new DialogInterface.OnClickListener() {
							
//							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							}
						}).show();
				} else if(!dayveCommon.checkInputEmail(edtTextChangeEmail.getText().toString().trim())) {
					new AlertDialog.Builder(DayveChangeEmailView.this)
					.setTitle(getResources().getString(R.string.change_email_unavailable_email_title))
					.setMessage(getResources().getString(R.string.change_email_unavailable_email_message))
					.setPositiveButton(getResources().getString(R.string.change_email_unavailable_email_button_ok), 
						new DialogInterface.OnClickListener() {
							
//							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							}
						}).show();
				} else {
					// 열려진 soft keyboard 를 닫는다.
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
					
					mHandler.sendMessage(mHandler.obtainMessage(THREAD_CHANGE_EMAIL));
				}
			}
			
		});
	}
	
	/**
	 * SharedPreferences 정보를 확인 한다.
	 */
	public void confirmNotification() {
		String myPf = "kr.pe.johnkim.dayve.activity_preferences";
		SharedPreferences mSharedPreferences = getSharedPreferences(myPf, Activity.MODE_PRIVATE);
		
		// id 를 가져 온다.
		DAYVE_ID = mSharedPreferences.getString("dayve_id", "");
		DAYVE_PASSWORD = mSharedPreferences.getString("dayve_password", "");
		DAYVE_EMAIL = mSharedPreferences.getString("dayve_email", "");

	}
	
	/**
	 * Handler 를 정의한다.
	 * 모든 Thread 를 등록해 놓고 필요할때 호출한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case THREAD_PROGRESS_BAR_VISIBLE : 
				progressBarChangeEmail.setVisibility(View.VISIBLE);
				txtViewChangeEmailNotification.setVisibility(View.VISIBLE);
				break;
			case THREAD_PROGRESS_BAR_INVISIBLE : 
				progressBarChangeEmail.setVisibility(View.INVISIBLE);
				txtViewChangeEmailNotification.setVisibility(View.INVISIBLE);
				break;
			case THREAD_CHANGE_EMAIL : 
				threadUpdateEmail();
				break;
			case THREAD_CHANGE_EMAIL_SUCCESS : 
				showChangeEmailToast();
				break;
			case THREAD_CHANGE_EMAIL_FAIL : 
				showDialogChangeEmailFail();
				break;
			}
		}
	};

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// main thread 에서 child thread 를 호출 한다.
		Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background_insertLog");
		thread.start();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		finish();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(!isForegrdound()) {
			DayvePreferenceView.activity.finish();
			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}
	
	private void threadUpdateEmail() {
		Log.i(TAG, "threadUpdateEmail");
		
		mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_VISIBLE));
		
		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				updateEmail();
			}
			
		});
		
		thread.start();
	}
	
	private void updateEmail() {
		Log.i(TAG, "updateEmail");
		
		DayveMember parameterMember = new DayveMember();
		
		parameterMember.setId(DAYVE_ID);
		parameterMember.setEmail(edtTextChangeEmail.getText().toString().trim());
		parameterMember.setModifyDate(currentDate);
		
		try {
			RESULT_CHANTE_EMAIL = dayveMemberRest.updateEmail(parameterMember).getResult();
			
			Log.i(TAG, "RESULT_CHANTE_EMAIL : " + RESULT_CHANTE_EMAIL);
			
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
			e.printStackTrace();
		}
		
		if(("SUCCESS").equals(RESULT_CHANTE_EMAIL)) {
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_CHANGE_EMAIL_SUCCESS));
			
			// 수정된 이메일을 설정 파일에 저장 한다.
			SharedPreferences mSharedPreferences = getSharedPreferences(myPreference, Activity.MODE_PRIVATE);

			SharedPreferences.Editor editor = mSharedPreferences.edit();
			editor.putString("dayve_email", edtTextChangeEmail.getText().toString());
			
			editor.commit();
			
			finish();
		} else {
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_CHANGE_EMAIL_FAIL));
		}
	}
	
	/**
	 * 이메일 변경에 실패하면 dialog 창을 띄운다.
	 */
	private void showDialogChangeEmailFail() {
		Log.e(TAG, "showDialogRegisterCategoryFail");
		
		new AlertDialog.Builder(DayveChangeEmailView.this)
		.setTitle(getResources().getString(R.string.change_email_fail_update_email_title))
		.setMessage(
				getResources().getString(R.string.change_email_fail_update_email_message_01) + 
				"\n" + 
				getResources().getString(R.string.change_email_fail_update_email_message_02)
				)
		.setPositiveButton(getResources().getString(R.string.change_email_fail_update_email_button_ok), 
			new DialogInterface.OnClickListener() {
				
//				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			}).show();
	}
	
	/**
	 * 이메일 변경에 성공하면 toast 를 띄운다.
	 */
	private void showChangeEmailToast() {
		CharSequence text = getResources().getString(R.string.change_email_success_update_email);
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	/**
	 * 로그를 저장 한다.
	 */
	private void insertLog() {
		Log.i(TAG, "insertLog");
		
		DayveLog dayveLog = new DayveLog();
		
		dayveLog.setId(DAYVE_ID);
		dayveLog.setViewName(TAG);
		dayveLog.setAccessDate(currentDate);
		
		try {
			dayveCommonRest.registerLog(dayveLog);
			Log.i(TAG, "Success to insert log.");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		}
	}
	
	/**
	 * 로그 저장은 UI 와 관계 없기 때문에 background thread 로 구현 함 : child thread
	 */
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			insertLog();
		}
	};
}
